package com.ruoyi.hxf.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Arrays;

import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hxf.domain.Pay;
import com.ruoyi.hxf.domain.Pd;
import com.ruoyi.hxf.domain.Type;
import com.ruoyi.hxf.mapper.PdMapper;
import com.ruoyi.hxf.mapper.RosterMapper;
import com.ruoyi.hxf.mapper.TypeMapper;
import com.ruoyi.hxf.service.IPdService;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.hxf.domain.vo.PayVo;
import com.ruoyi.hxf.domain.bo.PayBo;
import com.ruoyi.hxf.service.IPayService;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 缴费(推送服务模块)
 *
 * @author hxf
 * @date 2023-01-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/money/pay")
public class PayController extends BaseController {

    private final IPayService iPayService;
    private final IPdService iPdService;

    private final RosterMapper rosterMapper;
    private final TypeMapper typeMapper;
    private final PdMapper pdMapper;

    private final ISysOssService iSysOssService;

    @Scheduled(cron = "0 */1 * * * ?")
    public void myTimes() {
        List<Pay> list = iPayService.List();
        for (Pay pay : list) {
            Date date = DateUtils.getNowDate();
            if (date.after(pay.getEndTime())&&pay.getProgressStatus().equals("0")) {
                pay.setProgressStatus("1");
                iPayService.updatePay(pay);
            }
        }
    }

    /**
     * 查询缴费(推送服务模块)列表
     */
//    @SaCheckPermission("money:pay:list")
    @GetMapping("/list")
    public TableDataInfo<PayVo> list(PayBo bo, PageQuery pageQuery) {
        TableDataInfo<PayVo> payVoTableDataInfo = iPayService.queryPageList(bo, pageQuery);
        for (PayVo row : payVoTableDataInfo.getRows()) {
            Pd pd=new Pd();
            pd.setStatus(String.valueOf(1));
            pd.setPayId(String.valueOf(row.getPayId()));
            PageQuery pageQuery1=new PageQuery();
            TableDataInfo<Pd> pdTableDataInfo = iPdService.queryPageList(pd, pageQuery1, "undefined", "undefined");
            row.setPayNumber(pdTableDataInfo.getTotal());
            iPayService.MyUpdateByVo(row);
            if(StringUtils.isNotBlank(rosterMapper.selectClassName(Long.valueOf(row.getDeptId())))){
                row.setRemark(rosterMapper.selectClassName(Long.valueOf(row.getDeptId())));
            }else{
                row.setRemark("全部年级");
            }
        }
        return payVoTableDataInfo;
    }

    /**
     * 导出缴费(推送服务模块)列表
     */
//    @SaCheckPermission("money:pay:export")
    @Log(title = "缴费(推送服务模块)", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(PayBo bo, HttpServletResponse response) {
        List<PayVo> list = iPayService.queryList(bo);
        for (PayVo payVo : list) {
            if(StringUtils.isNotBlank(rosterMapper.selectClassName(Long.valueOf(payVo.getDeptId())))){
                payVo.setRemark(rosterMapper.selectClassName(Long.valueOf(payVo.getDeptId())));
            }else{
                payVo.setRemark("全部年级");
            }
        }
        ExcelUtil.exportExcel(list, "缴费推送表", PayVo.class, response);
    }

    /**
     * 获取缴费(推送服务模块)详细信息
     *
     * @param payId 主键
     */
//    @SaCheckPermission("money:pay:query")
    @GetMapping("/{payId}")
    public R<PayVo> getInfo(@NotNull(message = "主键不能为空")
                            @PathVariable Long payId) {
        return R.ok(iPayService.queryById(payId));
    }
    /**
     * 新增缴费(推送服务模块)
     */
//    @SaCheckPermission("money:pay:add")
    @Log(title = "缴费(推送服务模块)", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody PayBo bo) {
        bo.setProgressStatus(String.valueOf(0));
        if(bo.getPayPicture()!=null){
            String[] split = bo.getPayPicture().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : split) {
                List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(Long.parseLong(s)));
                for (int i = 0; i < list.size(); i++) {
                    if (stringBuffer.length() == 0) {
                        stringBuffer.append(list.get(i).getUrl());
                    } else {
                        stringBuffer.append("," + list.get(i).getUrl());
                    }
                }
            }
            bo.setPayUrl(stringBuffer.toString());
        }
        if(bo.getPushStatus().equals("0")){
            bo.setRemark("已推送");
        }

        return toAjax(iPayService.insertByBo(bo));
    }

    /**
     * 修改缴费(推送服务模块)
     */
//    @SaCheckPermission("money:pay:edit")
    @Log(title = "缴费(推送服务模块)", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody PayBo bo) {
        if(bo.getPayPicture()!=null){
            String[] split = bo.getPayPicture().split(",");
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : split) {
                List<SysOssVo> list = iSysOssService.listByIds(Arrays.asList(Long.parseLong(s)));
                for (int i = 0; i < list.size(); i++) {
                    if (stringBuffer.length() == 0) {
                        stringBuffer.append(list.get(i).getUrl());
                    } else {
                        stringBuffer.append("," + list.get(i).getUrl());
                    }
                }
            }
            bo.setPayUrl(stringBuffer.toString());
        }else{
            bo.setPayUrl(null);
        }
        bo.setUpdateBy(LoginHelper.getUsername());
        bo.setUpdateTime(DateUtils.getNowDate());
        PayVo payVo = iPayService.queryById(bo.getPayId());
        if(payVo.getRemark()==null&&bo.getPushStatus().equals("0")){
            bo.setRemark("已推送");
            if (bo.getPushStatus().equals("0") && bo.getDeptId() != -1) {
                List<Type> types = typeMapper.selectParentIdByDeptId(bo.getDeptId());
                for (Type type : types) {
                    if (type.getDeptId() != null) {
                        String classParents = typeMapper.selectClassParentByDeptId(Long.valueOf(type.getDeptId()));
                        if (StringUtils.isNotBlank(classParents)) {
                            for (String s : classParents.split(",")) {
                                Pd pd1 = pdMapper.selectVoByPayId(Long.valueOf(s), bo.getPayId());
                                if(pd1==null){
                                    Pd pd = new Pd();
                                    pd.setPayId(String.valueOf(bo.getPayId()));
                                    pd.setCreateBy(s);
                                    pdMapper.insertPd(pd);
                                }

                            }
                        }
                    }
                }
            } else if (bo.getPushStatus().equals("0") && bo.getDeptId() == -1) {
                List<Type> types = typeMapper.selectList();
                for (Type type : types) {
                    if (type.getDeptId() != null) {
                        String classParents = typeMapper.selectClassParentByDeptId(Long.valueOf(type.getDeptId()));
                        if (StringUtils.isNotBlank(classParents)) {
                            for (String s : classParents.split(",")) {
                                Pd pd1 = pdMapper.selectVoByPayId(Long.valueOf(s), bo.getPayId());
                                if(pd1==null){
                                    Pd pd = new Pd();
                                    pd.setPayId(String.valueOf(bo.getPayId()));
                                    pd.setCreateBy(s);
                                    pdMapper.insertPd(pd);
                                }
                            }
                        }
                    }
                }
            }
        }
        return toAjax(iPayService.MyUpdateByBo(bo));
    }

    /**
     * 删除缴费(推送服务模块)
     *
     * @param payIds 主键串
     */
//    @SaCheckPermission("money:pay:remove")
    @Log(title = "缴费(推送服务模块)", businessType = BusinessType.DELETE)
    @DeleteMapping("/{payIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] payIds) {
        return toAjax(iPayService.deleteWithValidByIds(Arrays.asList(payIds), true));
    }

    /**
     * 查询我要缴费的列表
     * @param bo
     * @param pageQuery
     * @return
     */
    @GetMapping("/payList")
    public TableDataInfo<PayVo> PayList(PayBo bo, PageQuery pageQuery) {
        bo.setDeptId(rosterMapper.selectGradeId(bo.getDeptId()));
        TableDataInfo<PayVo> payVoTableDataInfo = iPayService.queryPagePayList(bo, pageQuery);
        if("我要查缴费状态".equals(bo.getRemark())){
            Long userId = LoginHelper.getUserId();
            for (PayVo row : payVoTableDataInfo.getRows()) {
                Pd pd = iPdService.queryById(userId, row.getPayId());
                if(pd!=null){
                    row.setRemark(pd.getStatus());
                    row.setPayMoney(row.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
                }else{
                    Pd pd1 = new Pd();
                    pd1.setPayId(String.valueOf(row.getPayId()));
                    pd1.setCreateBy(String.valueOf(userId));
                    pdMapper.insertPd(pd1);
                    row.setRemark(String.valueOf(0));
                    row.setPayMoney(row.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            }
        }else{
            for (PayVo row : payVoTableDataInfo.getRows()) {
                row.setPayMoney(row.getPayMoney().setScale(2, BigDecimal.ROUND_HALF_UP));
            }
        }

        return payVoTableDataInfo;
    }
}
